package admin

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

func (h *AdminHandler) GetConversations(c echo.Context) error {
	reqDto := new(GetConversationsRequest)
	if err := c.Bind(reqDto); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Invalid request format")
	}
	if reqDto.Page <= 0 {
		reqDto.Page = 1
	}
	if reqDto.Limit <= 0 || reqDto.Limit > 100 {
		reqDto.Limit = 20
	}

	var dbRows []entity.Conversation
	var total int64

	// 获取总数
	if err := h.db.Model(&entity.Conversation{}).Count(&total).Error; err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	tx := h.db.Model(&entity.Conversation{})
	// 如果指定了用户ID，则添加查询条件
	if reqDto.UserID != "" {
		tx = tx.Where("user_id = ?", reqDto.UserID)
	}

	// 获取对话列表
	offset := (reqDto.Page - 1) * reqDto.Limit
	if err := tx.Offset(offset).Limit(reqDto.Limit).Order("created_at DESC").Find(&dbRows).Error; err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	// 转换为响应格式
	rows := make([]ConversationRow, 0, len(dbRows))
	for _, conv := range dbRows {
		rows = append(rows, ConversationRow{
			ID:        conv.ID,
			UserID:    conv.UserID,
			Title:     conv.Title,
			CreatedAt: conv.CreatedAt.Unix(),
			UpdatedAt: conv.UpdatedAt.Unix(),
		})
	}

	return response.Success(c, GetConversationsResponse{
		Rows:       rows,
		Total:      total,
		Page:       reqDto.Page,
		Limit:      reqDto.Limit,
		TotalPages: (total + int64(reqDto.Limit) - 1) / int64(reqDto.Limit),
	})
}

// GetConversationDetail 获取单个对话详情
func (h *AdminHandler) GetConversationDetail(c echo.Context) error {
	var req GetConversationDetailRequest
	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Invalid request format")
	}

	if err := h.validator.Struct(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "Validation failed: "+err.Error())
	}

	var conversation entity.Conversation
	if err := h.db.Where("id = ?", req.ConversationID).First(&conversation).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return echo.NewHTTPError(http.StatusNotFound, "Conversation not found")
		}
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	return response.Success(c, ConversationRow{
		ID:        conversation.ID,
		UserID:    conversation.UserID,
		Title:     conversation.Title,
		CreatedAt: conversation.CreatedAt.Unix(),
		UpdatedAt: conversation.UpdatedAt.Unix(),
	})
}
